import { includes, isEmpty,find } from "lodash";
import React, { useEffect,useCallback, useState } from "react";
import PropTypes from "prop-types";

import Alert from "antd/lib/alert";
import Link from "@/components/Link";
import LoadingOutlinedIcon from "@ant-design/icons/LoadingOutlined";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import EmptyState, { EmptyStateHelpMessage } from "@/components/empty-state/EmptyState";
import DynamicComponent from "@/components/DynamicComponent";
import BeaconConsent from "@/components/BeaconConsent";
import moment from "moment";
import { axios } from "@/services/axios";
import recordEvent from "@/services/recordEvent";
import { currentUser, messages } from "@/services/auth";
import notification from "@/services/notification";
import { Dashboard } from "@/services/dashboard";
import { Query } from "@/services/query";
import routes from "@/services/routes";
import HomeTableList from "@/components/home/HomeTableList";
import FinishToolbar from "@/components/contract/FinishToolbar";
import "./Home.less";

import { Card, Divider, Col, Row } from 'antd/lib';
import VisualizationRenderer from "@/components/visualizations/VisualizationRenderer";
// import OrgUnit from "@/services/orgunit";
import ContractApply from "@/services/contractapply";
import Contracts from "@/services/contracts";
import Workflow from "@/services/workflow";
import GlobalSetting from "@/services/globalsetting";


function DeprecatedEmbedFeatureAlert() {
  return (
    <Alert
      className="m-b-15"
      type="warning"
      message={
        <>
          你已设置参数 <code>ALLOW_PARAMETERS_IN_EMBEDS</code>，但该特征暂时不可用。{" "}
          {/* <Link
            href="https://discuss.redash.io/t/support-for-parameters-in-embedded-visualizations/3337"
            target="_blank"
            rel="noopener noreferrer">
            Read more
          </Link> */}
          .
        </>
      }
    />
  );
}

function EmailNotVerifiedAlert() {
  const verifyEmail = () => {
    axios.post("verification_email/").then(data => {
      notification.success(data.message);
    });
  };

  // return (
  //   <Alert
  //     className="m-b-15"
  //     type="warning"
  //     message={
  //       <>
  //         电子邮箱校验邮件已发送，请查收并点击邮件里的链接，已确认邮箱输入正确。{" "}
  //         <a className="clickable" onClick={verifyEmail}>
  //           重新发送邮件
  //         </a>
  //         .
  //       </>
  //     }
  //   />
  // );
}

function FavoriteList({ title, resource, itemUrl, emptyState }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    resource
      .favorites()
      .then(({ results }) => setItems(results))
      .finally(() => setLoading(false));
  }, [resource]);

  return (
    <>
      <div className="d-flex align-items-center m-b-20">
        <p className="flex-fill f-500 c-black m-0">{title}</p>
        {loading && <LoadingOutlinedIcon />}
      </div>
      {/* {!isEmpty(items) && (
        <div className="list-group">
          {items.map(item => (
            <Link key={itemUrl(item)} className="list-group-item" href={itemUrl(item)}>
              <span className="btn-favourite m-r-5">
                <i className="fa fa-star" aria-hidden="true" />
              </span>
              {item.name}
              {item.is_draft && <span className="label label-default m-l-5">草稿</span>}
            </Link>
          ))}
        </div>
      )} */}
      {isEmpty(items) && !loading && emptyState}
    </>
  );
}

FavoriteList.propTypes = {
  title: PropTypes.string.isRequired,
  resource: PropTypes.func.isRequired, // eslint-disable-line react/forbid-prop-types
  itemUrl: PropTypes.func.isRequired,
  emptyState: PropTypes.node,
};
FavoriteList.defaultProps = { emptyState: null };

// function DashboardAndQueryFavoritesList() {
//   return (
//     <div className="tile">
//       <div className="t-body tb-padding">
//         <div className="row home-favorites-list">
//           <div className="col-sm-6 m-t-20">
//             <FavoriteList
//               title="我关注的报表"
//               resource={Dashboard}
//               itemUrl={dashboard => dashboard.url}
//               emptyState={
//                 <p>
//                   <span className="btn-favourite m-r-5">
//                     <i className="fa fa-star" aria-hidden="true" />
//                   </span>
//                   <Link href="dashboards">关注的报表</Link>
//                 </p>
//               }
//             />
//           </div>
//           <div className="col-sm-6 m-t-20">
//             <FavoriteList
//               title="我关注的查询"
//               resource={Query}
//               itemUrl={query => `queries/${query.id}`}
//               emptyState={
//                 <p>
//                   <span className="btn-favourite m-r-5">
//                     <i className="fa fa-star" aria-hidden="true" />
//                   </span>
//                   <Link href="queries">关注的查询</Link>
//                 </p>
//               }
//             />
//           </div>
//         </div>
//       </div>
//     </div>
//   );
// }

export default function Home() {
  const [warncount, setwarncount] = useState(0);
  const [applyflag, setapplyflag] = useState(true);
  const [contractcount, setcontractcount] = useState(0);
  const [contractflag, setcontractflag] = useState(true);
  const [checkcount, setcheckcount] = useState(0);
  const [checkflag, setcheckflag] = useState(true);
  const [queryid, setqueryid] = useState(0);
  const [visualizationid, setvisualizationid] = useState(0);
  const [query, setQuery] = useState(null);
  const [visualization, setvisualization] = useState(null);
  const [queryresults, setqueryresults] = useState(null);
  const [error, setError] = useState(null);
  const [viewurlflag, setviewurlflag] = useState(true);
  useEffect(() => {
    recordEvent("view", "page", "personal_homepage");
    let  params={
      page: 1,
      pagesize: 5,
      code: "",
      name: "",
      party_a: "",
      type: "",
      userid: currentUser.id,
      id:0,
      departmentid:[],
      amount:0,
      amountmax:0,
      datadown: false,
      warns:"1",
    }
    if(applyflag) {
      setapplyflag(false);
        Contracts.getlist(params).then(data => {
          setwarncount(data.total);
        });
      }
    params={
    page: 1,
    pagesize: 5,
    code: "",
    name: "",
    party_a: "",
    type: "",
    userid: currentUser.id,
    id:0,
    departmentid:[],
    amount:0,
    amountmax:0,
    datadown: false,
  }
    if(contractflag) {
      setcontractflag(false);
      Contracts.getlist(params).then(data => {
        setcontractcount(data.total);
      });
    }
    params={
    page: 1,
    pagesize: 5,
    statename: "",
    seltype: "1",
    bill_enum: "",
    userid: currentUser.id,
  }
    if(checkflag) {
      setcheckflag(false);
      Workflow.getchecklist(params).then(data => {
        setcheckcount(data.total);
        
      });
    }
    params={
      page: 1,
      pagesize: 5,
      code: '视图url',
      type: '主页',
    }
    if(viewurlflag) {
      setviewurlflag(false);
      GlobalSetting.getlist(params).then(data => {
        const ids = data.data[0].value.split(',');
        const qid = Number(ids[0]);
        let vid= ids.length>1 ? Number(ids[1]):0;
        setqueryid(qid);
        setvisualizationid(vid);
        if(qid>0){
          Query.get({ id: qid })
          .then(result => {
              setQuery(result);
              if (vid>0){
                const vistion = find(result.visualizations, vis => vis.id === vid);
                setvisualization(vistion);
              }else{
                setvisualization(result.visualizations[0]);
              }
          })
          .catch(error => {
            setError(error.message +":" + error.detailedMessage);
          });
        }
      });
    }
}, [checkflag]);

        // const visualization = find(query.visualizations, vis => vis.id === visualizationId);
        // const [visualization, setvisualization] = useState(null);
        // const [queryresults, setqueryresults] = useState(null);


const refreshQueryResults = useCallback(() => {
  if (query) {
    setError(null);
    query
      .getQueryResultPromise()
      .then(result => {
        setqueryresults(result);
      })
      .catch(error => {
        setError(error.message +":" + error.detailedMessage);
      });
  }
}, [query]);

useEffect(() => {
  refreshQueryResults();
}, [refreshQueryResults]);

//  if (!query) {
//   return null;
// }
  return (
    <div className="home-page" stlye={{overflowY: "hidden"}}>
      <img style={{height:'120px'}} className="home-image" src="/static/images/footlogo.jpg"/>
      <div className="container" style={{ background:"#00000000" }}>
        <div className="contractcard" style={{  padding: '30px' }}>
        {!currentUser.hasPermission("lawyer") && (<Row align="middle" gutter={16}>
          <Col span={4} align="center">
            <Link href="/contract/new/0" style={{ color:"black" }}>
              <img src="/static/images/xingzhuang1.png"  alt="新建合同" title="新建合同" />
            </Link>
            <Card title="合同起草" bordered={false} style={{background: "#00000000",fontSize:"20px",color:"2196f3"}}>
            <p>            <Link href="/contract/new/0" style={{ color:"2196f3" }}>新建合同
            </Link>
              </p>
              <p>
              <Link href="/notice/neworg" style={{ color:"2196f3" }}>
              附件池
              </Link></p>
            </Card>
          </Col>
          <Col span={4} align="center" >
            <Link href="/workflow/billcheck/contracts" style={{ color:"black" }}>
              <img src="/static/images/xingzhuang2.png"  alt="待我审核" title="待我审核" />
            </Link>

            <Card title="合同审批" bordered={false} style={{background: "#00000000",fontSize:"20px",color:"2196f3"}}>
            <p>
              <Link href="/workflow/billcheck/contracts" style={{ color:"2196f3" }}>
                 待我审核{checkcount}条
              </Link>
              </p>
              <p>
              <Link href="/workflow/billcheck/ok/contracts" style={{ color:"2196f3" }}>
              审批信息
              </Link></p>
            </Card>
          </Col>
          <Col span={4} align="center">
            <Link href="/contracts/approve" style={{ color:"black" }}>
              <img src="/static/images/xingzhuang3.png"  alt="合同查询" title="合同查询" />
            </Link>
            <Card title="合同查询" bordered={false} style={{background: "#00000000",fontSize:"20px",color:"2196f3"}}>
            <p>
            <Link href="/contracts/approve" style={{ color:"2196f3" }}>
            已提交{contractcount}条
            </Link></p>
              <p>
            <Link href="/contracts/warns" style={{ color:"2196f3" }}>
              到期合同{warncount}条
            </Link></p>
            </Card>
          </Col>
          <Col span={12} align="center">
              <img src="/static/images/homeright.png" width="305" height="282"/>
          </Col>
        </Row>)}
        <div className="p-15">
        {/* <FinishToolbar  id={0} /> */}
           <HomeTableList  seltype={"1"}/>
        </div>

     </div>
    </div>
  </div>
  );
}

routes.register(
  "Home",
  routeWithUserSession({
    path: "/",
    title: "合同管理",
    render: pageProps => <Home {...pageProps} />,
  })
);
